package com.bingkaimedia.dompetobeta.app;




import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 

import com.bingkaimedia.dompetobeta.R; 
import com.bingkaimedia.dompetobeta.libs.AlertDialogManager;
import com.bingkaimedia.dompetobeta.libs.JSONfunctions;
import com.bingkaimedia.dompetobeta.libs.SessionManager;
import com.bingkaimedia.dompetobeta.libs_image.Utils;

import android.R.drawable;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast; 


@SuppressLint("NewApi")
public class Signin extends Activity  
{

	//private SQLiteDB_Account account;
	private TextView lbl_signin_judul; 
	private TextView lbl_signin_judul2; 
	private Button cmd_signin_signin;
	private Button cmd_signin_signup;
	private EditText txt_signin_username;
	private EditText txt_signin_password; 
	protected String user1;
	protected String pwd1;
	private String appid;
	private String ip;
	private String manufacturer;
	private String model;
	private String deviceid;
	private String os;
	private String latitude;
	private String longitude;

	private LocationManager locationMangaer=null;  
	private LocationListener locationListener=null; 
	private Boolean flag = false;  
	
	HttpPost httppost;
	StringBuffer buffer;
	HttpResponse response;
	HttpClient httpclient;
	List<NameValuePair> nameValuePairs; 
	public String result; 
	
	

	public static final String KEY_SIGNIN_resp = "resp";   
	public static final String KEY_SIGNIN_token = "token";   
	public static final String KEY_SIGNIN_loginstatus = "loginstatus";   
	public static final String KEY_SIGNIN_loginnotification = "loginnotification";   
	public static final String KEY_SIGNIN_updateappsidstatus = "updateappsidstatus";   
	public static final String KEY_SIGNIN_appsidstatus = "appsidstatus";   
	public static final String KEY_SIGNIN_appsidonapps = "appsidonapps";   
	public static final String KEY_SIGNIN_firstimestatus = "firstimestatus";   
	public static final String KEY_SIGNIN_verificationstatus = "verificationstatus";   
	public static final String KEY_SIGNIN_verificationnotification = "verificationnotification";   
	public static final String KEY_SIGNIN_pinstatus = "pinstatus";   
	public static final String KEY_SIGNIN_pinnotification = "pinnotification";   
	public static final String KEY_SIGNIN_appsver = "appsver";   
	public static final String KEY_SIGNIN_debug = "debug";   
	

	private String xml_signin_resp;
	private String xml_signin_token;
	private String xml_signin_loginstatus;
	private String xml_signin_loginnotification;
	private String xml_signin_updateappsidstatus;
	private String xml_signin_appsidstatus;
	private String xml_signin_appsidonapps;
	private String xml_signin_firstimestatus;
	private String xml_signin_verificationstatus;
	private String xml_signin_verificationnotification;
	private String xml_signin_pinstatus;
	private String xml_signin_pinnotification;
	private String xml_signin_appsver;
	private String xml_signin_debug;
	
	public String url; 
	protected String u1;
	protected String p1;
	public ProgressDialog pd;

	private static String session_userid;
	private static String session_username;
	private static String session_password;
	private static String session_email;
	private static String session_country;
	private static String session_country_name;
	private static String session_city;
	private static String session_city_name;
	private static String session_checked;
	
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();
		
	// Session Manager Class
	SessionManager session;
	
	 
    ProgressDialog progressDoalog;
    
    Button button;
    int typeBar;
    int delay = 0;                  // Milliseconds of delay in the update loop
    int maxBarValue = 0;           // Maximum value of horizontal progress bar

    
    int count;
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
	}
	
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }
	
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); 
		setContentView(R.layout.signin);
		
		
		inisialisasi();	
		form_click();
		 
		session = new SessionManager(getApplicationContext());                
  
	 
	}
	
	
	private void inisialisasi(){ 
	
		lbl_signin_judul=(TextView)findViewById(R.id.lbl_signin_judul);
		lbl_signin_judul2=(TextView)findViewById(R.id.lbl_signin_judul2);
		txt_signin_username=(EditText)findViewById(R.id.txt_signin_username);
		txt_signin_password=(EditText)findViewById(R.id.txt_signin_password);
		cmd_signin_signin=(Button)findViewById(R.id.cmd_signin_sigin); 
		cmd_signin_signup=(Button)findViewById(R.id.cmd_signin_signup); 
		 

		Typeface font = Typeface.createFromAsset(getAssets(), "gisha.ttf");  
 
		lbl_signin_judul.setTypeface(font);
		lbl_signin_judul2.setTypeface(font);
		txt_signin_username.setTypeface(font);
		txt_signin_password.setTypeface(font);
		cmd_signin_signin.setTypeface(font);
		cmd_signin_signup.setTypeface(font);
		 
		 
	   
        
		appid = Installation.id(getApplicationContext());
		ip = Utils.getIPAddress(true);
		manufacturer = Build.MANUFACTURER;
		model = Build.MODEL;
		deviceid = Secure.getString(getApplicationContext().getContentResolver(),Secure.ANDROID_ID);
		os = Build.VERSION.RELEASE; 
		
		
        
		GPSTracker gps;
		gps = new GPSTracker(Signin.this);
		 
        // check if GPS enabled     
        if(gps.canGetLocation()){ 
            latitude = String.valueOf(gps.getLatitude());
            longitude = String.valueOf(gps.getLongitude()); 
        }else{ 
            gps.showSettingsAlert();
        } 
        

		System.out.println(appid);
		System.out.println(ip);
		System.out.println(manufacturer);
		System.out.println(model);
		System.out.println(deviceid);
		System.out.println(os);
		System.out.println(latitude);
		System.out.println(longitude);
	}
	 
	 
	
	private void form_click(){
		
		cmd_signin_signup.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				 //System.out.println("masuk button text 2");
				 Intent intent=new Intent(getApplicationContext(),Signup.class);
				 startActivity(intent);
				 finish();
			}
		});
		
		//resume();
		 
		cmd_signin_signin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{ 

				//account.openToRead(); 
				user1=txt_signin_username.getText().toString().trim();
				pwd1=txt_signin_password.getText().toString().trim();
				//account.close();
			
				
				//System.out.println("isonline "+isonline());
				if(isonline()==false){
					alert.showAlertDialog(Signin.this, "Information", "Tidak terhubung dengan internet.", false);
				}
				else if(isonline()==true){
					//alert.showAlertDialog(Login.this, "Information", "Ada koneksi internet", true); 
	                new Check().execute();
	                //System.out.println("klik"); 
				}
				else{
					//System.out.println("masuk else isonline");
				}
				  
			}
			 
		}); 
	}
	
	
	@SuppressLint("NewApi")
	class Check extends AsyncTask{
	
		
		private String json;
		private JSONObject jsonobject;
		public String code;
		public String msg;
		
		private String id_users;
		private String username;
		private String password;
		private String email;
		private String country;
		private String country_name;
		private String city;
		private String city_name;
		
		
	 
		@Override
		protected void onPreExecute() 
		{
			super.onPreExecute();
			
			 
			 
			
			progressDoalog = new ProgressDialog(Signin.this);
	        //progressDoalog.setMax(20);
	        progressDoalog.setMessage("Please wait...");
	        progressDoalog.setTitle("Login");
	        progressDoalog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	        progressDoalog.show();
	
	        new Thread(new Runnable() {
	        	@Override
	        	public void run() {
	        		count=30;
	        		try {
	        			while (count >= 0) {
	        				Thread.sleep(1000);
	        				//System.out.println("count "+count); 
	        				handle.sendMessage(handle.obtainMessage());
	        				count--;
	        				if (count <= 1) {
	        					progressDoalog.dismiss();
	        					//String mess = "waktu habis";
	        					//Toast.makeText(getApplicationContext(), mess, Toast.LENGTH_SHORT).show();
	        				}
	        			} 
	        		} 
	        		catch (Exception e) {
	        			e.printStackTrace();
	        			//System.out.println("catch (Exception e) run : "+e);
	        		}
	        	}
	        }).start();
		
	        
		}
	
		
		@Override
		protected Object doInBackground(Object... params) {
			
			code="0";
			msg="Not connected to server";
			//System.out.println("Mulai do in background");
			try{			
				 
				httpclient=new DefaultHttpClient();
				httppost= new HttpPost(Global.link_login); // make sure the url is correct.
				
				//add your data
				nameValuePairs = new ArrayList<NameValuePair>(2);
				
				// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
				nameValuePairs.add(new BasicNameValuePair("username",txt_signin_username.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
				nameValuePairs.add(new BasicNameValuePair("password",txt_signin_password.getText().toString().trim())); 
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				
				//Execute HTTP Post Request
				response=httpclient.execute(httppost);
				
				// edited by James from coderzheaven.. from here....
				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				result = httpclient.execute(httppost, responseHandler);
				System.out.println("Response : " + result); 
				
				runOnUiThread(new Runnable() {
				    public void run() {
				    	System.out.println("Response from PHP : " + result);
				    	progressDoalog.dismiss();
				    }
				});
				
				try { 
					jsonobject = new JSONObject(result); 
					//code = "1";
					xml_signin_resp = jsonobject.getString(KEY_SIGNIN_resp);
					xml_signin_debug = jsonobject.getString(KEY_SIGNIN_debug);
					  
					System.out.println(xml_signin_resp);
					System.out.println(xml_signin_debug);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				  
				
				
				
				if(result.equalsIgnoreCase("User Found")){
					runOnUiThread(new Runnable() {
					    public void run() {
					    	Toast.makeText(Signin.this,"Login Success", Toast.LENGTH_SHORT).show();
					    }
					});
					
					startActivity(new Intent(Signin.this, Notification.class));
				}else{
					startActivity(new Intent(Signin.this, Notification.class));			
				}
				
				
			}catch(Exception e){
				progressDoalog.dismiss();
				System.out.println("Exception : " + e.getMessage());
			}
			 
			return null;
		}
	
	
		
		protected void onPostExecute(Void unused)
		{
			super.onPostExecute(result);
			//System.out.println("onpostexecute"); 
			count = 0;  
			result = json;
 
			 
			
			 
		}
	 
		 
		Handler handle = new Handler() {
	    	@Override
	    	public void handleMessage(Message msg) {
	    		super.handleMessage(msg);
	    		////System.out.println("message handle "+msg);
	    		//progressDoalog.incrementProgressBy(1);
	
				progressDoalog.setMessage("Please wait..."+count);
	    	}
	    };
	    
	}

 
	public void resume()
	{
		
		//session.checkLogin();
	    
	    // get user data from session
	
		//System.out.println("isLoggedIn");
		//System.out.println(session.isLoggedIn());
		
		if(session.isLoggedIn() == true)
		{
		
			session = new SessionManager(getApplicationContext());
		    
		    HashMap<String, String> user = session.getUserDetails();
		     
		    // name
		    session_userid = user.get(SessionManager.id_users);
		    session_username = user.get(SessionManager.username);
		    session_password = user.get(SessionManager.password);
		    session_email = user.get(SessionManager.email);
		    session_city = user.get(SessionManager.city);
		    session_checked = user.get(SessionManager.checked);
			
		    //System.out.println("session");
		    //System.out.println(session_userid);
		    //System.out.println(session_username);
		    //System.out.println(session_password);
		    //System.out.println(session_email);
		    //System.out.println(session_city);
		    //System.out.println("cek "+session_checked);
		    
		    Boolean boo = Boolean.parseBoolean(session_checked);
		    // displaying user data
		    if(boo == true)
		    {
		    	//System.out.println("masuk fungsi if");
		    	Intent intent=new Intent(getApplicationContext(),Home2.class);
				startActivity(intent);
		    	
			    //this.user.setText(session_username);
			    //this.pwd.setText(session_password);
			    //checkbox.setChecked(true);
		    } 
		    else if (boo == false)
		    {
		    	//System.out.println("masuk fungsi else if");
	
			    this.txt_signin_username.setText(session_username);
			    this.txt_signin_password.setText(session_password);
		    }
		    else
		    {
		    	//System.out.println("masuk fungsi else");
		
			    this.txt_signin_username.setText(session_username);
			    this.txt_signin_password.setText(session_password);
			    //checkbox.setChecked(true);
		    }
		}
	}

	public boolean isonline()
	{
		
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	 
}
